package com.py.korona.ui.activities.room;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import com.py.korona.R;
import com.py.korona.db.UriBuilder;
import com.py.korona.db.model.RoomEntity;
import com.py.korona.ui.activities.categoriesinroom.CategoriesInRoomWrapper;
import com.py.korona.ui.controls.activities.CustomActivity;
import cz.destil.settleup.gui.MultiChoiceItem;

public class RoomDetailActivity extends CustomActivity implements RoomDetailFragmentListener {
    private List<MultiChoiceItem> changeListCategoriesInRoom;
    private RoomEntity            roomEntity;

    @Override
    public Bitmap fragmentGetRoomBitmap(Fragment fragment) {
        if (null == roomEntity) {
            return null;
        }
        byte[] imageData = roomEntity.getImageData();
        if (null != imageData) {
            ByteArrayInputStream imageStream = new ByteArrayInputStream(imageData);
            return BitmapFactory.decodeStream(imageStream);
        } else {
            return null;
        }
    }

    @Override
    public String fragmentGetRoomCategories(Fragment fragment) {
        if (null == roomEntity) {
            return null;
        }
        return CategoriesInRoomWrapper.getSelectedCategoriesAsCommaString(roomEntity.get_id(), getContentResolver());
    }

    @Override
    public List<MultiChoiceItem> fragmentGetRoomCategoriesList(Fragment fragment) {
        if (null == roomEntity) {
            return null;
        }
        return CategoriesInRoomWrapper.categoriesForRoom(roomEntity.get_id(), getContentResolver());
    }

    @Override
    public String fragmentGetRoomDescription(Fragment fragment) {
        if (null == roomEntity) {
            return null;
        }
        return roomEntity.getDescription();
    }

    @Override
    public String fragmentGetRoomName(Fragment fragment) {
        if (null == roomEntity) {
            return null;
        }
        return roomEntity.getText();
    }

    @Override
    public float fragmentGetRoomRating(Fragment fragment) {
        if (null == roomEntity) {
            return 0.0f;// minimum for rating
        }
        return roomEntity.getRating();
    }

    @Override
    public void fragmentOnCloseAction(Fragment fragment) {
        finish();
    }

    @Override
    public void fragmentOnDeleteAction(Fragment fragment) {
        if (null == roomEntity) {
            return;
        }
        roomEntity.removeFromDatabase();
        setHasModified(false);
    }

    @Override
    public void fragmentOnEditAction(Fragment fragment) {
        this.setDetailState(CustomActivityDetailState.CustomActivityDetailStateEdit);
    }

    @Override
    public void fragmentOnReadonlyAction(Fragment fragment) {
        this.setDetailState(CustomActivityDetailState.CustomActivityDetailStateView);
    }

    @Override
    public void fragmentOnSave(Fragment fragment) {
        if (null == roomEntity) {
            return;
        }
        try {
            roomEntity.save();
            if (null != changeListCategoriesInRoom) {
                for (MultiChoiceItem item : changeListCategoriesInRoom) {
                    CategoriesInRoomWrapper.saveCategorySelection(roomEntity.get_id(), getContentResolver(), item);
                }
            }
            this.setHasModified(false);
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void fragmentOnViewAction(Fragment fragment) {
        this.setDetailState(CustomActivityDetailState.CustomActivityDetailStateView);
    }

    @Override
    public void fragmentSetRoomBitmap(Fragment fragment, Bitmap bitmap) {
        if (null == roomEntity) {
            return;
        }
        if (null != bitmap) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 10, stream);
            roomEntity.setImageData(stream.toByteArray());
        } else {
            roomEntity.setImageData(null);
        }
    }

    @Override
    public void fragmentSetRoomCategories(Fragment fragment, List<MultiChoiceItem> listOfChangedCategories) {
        if (null == listOfChangedCategories) {
            return;
        }
        changeListCategoriesInRoom = new ArrayList<MultiChoiceItem>();
        changeListCategoriesInRoom.addAll(listOfChangedCategories);
    }

    @Override
    public void fragmentSetRoomDescription(Fragment fragment, String description) {
        if (null == roomEntity) {
            return;
        }
        roomEntity.setDescription(description);
    }

    @Override
    public void fragmentSetRoomName(Fragment fragment, String name) {
        if (null == roomEntity) {
            return;
        }
        roomEntity.setText(name);
    }

    @Override
    public void fragmentSetRoomRating(Fragment fragment, float rating) {
        if (null == roomEntity) {
            return;
        }
        roomEntity.setRating(rating);
    }

    private void loadData(Uri uri) {
        if (null != uri) {
            roomEntity = new RoomEntity(getContentResolver(), uri);
        } else {
            roomEntity = new RoomEntity(getContentResolver());
        }
    }

    @Override
    public boolean isDetailStateAllowed(CustomActivityDetailState state) {
        if (this.isHasModified()) {
            //        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            //        dialog.setOnCancelListener(new OnCancelListener() {
            //            @Override
            //            public void onCancel(DialogInterface dialog) {
            //            }
            //        });
            //        dialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            //            @Override
            //            public void onClick(DialogInterface dialog, int which) {
            //                dialog.cancel();
            //            }
            //        });
            //        dialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            //            @Override
            //            public void onClick(DialogInterface dialog, int which) {
            //                dialog.dismiss();
            //            }
            //        });
            //        dialog.setTitle(R.string.title_alert_category_check);
            //        dialog.show();
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onEnteringEditMode() {
        RoomDetailFragmentEditor fragment = new RoomDetailFragmentEditor();
        fragment.setListener(this);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.room_detail_container, fragment);
        ft.commit();
    }

    @Override
    public void onEnteringViewMode() {
        RoomDetailFragmentViewer fragment = new RoomDetailFragmentViewer();
        fragment.setListener(this);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.room_detail_container, fragment);
        ft.commit();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_detail_container);
        /** action bar init */
        ActionBar bar = getActionBar();
        bar.setDisplayHomeAsUpEnabled(true);
        /** load fragment */
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            /**
             * 
             * extract uri load data
             */
            String contentItemType = UriBuilder.contentType(RoomEntity.uriBasePath());
            Uri uri = bundle.getParcelable(contentItemType);
            loadData(uri);
            /**
             * 
             * extract readonly
             */
            boolean readonly = bundle.getBoolean("readonly");
            if (readonly) {
                this.setDetailState(CustomActivityDetailState.CustomActivityDetailStateView);
            } else {
                this.setDetailState(CustomActivityDetailState.CustomActivityDetailStateEdit);
            }
        } else {
            this.setDetailState(CustomActivityDetailState.CustomActivityDetailStateEdit);
        }
    }
}
